package grimbo.goodwinfooty.server.fileupload;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

public class FileUploadHelper {
	public Map parseRequestMemory(HttpServletRequest req)
			throws FileUploadException {
		return parseRequest(req, new MemoryFileItemFactory());
	}

	public Map parseRequestDisk(HttpServletRequest req)
			throws FileUploadException {
		return parseRequest(req, new DiskFileItemFactory());
	}

	public Map parseRequest(HttpServletRequest req, FileItemFactory fif)
			throws FileUploadException {
		ServletFileUpload sfu = new ServletFileUpload(fif);
		List fileItems = sfu.parseRequest(req);
		Map result = new HashMap();
		for (Iterator it = fileItems.iterator(); it.hasNext();) {
			FileItem fi = (FileItem) it.next();
			if (fi.isFormField()) {
				List params = (List) result.get(fi.getFieldName());
				if (null == params) {
					params = new ArrayList();
				}
				params.add(fi.getString());
				result.put(fi.getFieldName(), params);
			} else {
				result.put(fi.getFieldName(), fi);
			}
		}
		return result;
	}
}
